<template>
  <div class="chat-container">
    <!-- 聊天记录区域 -->
    <el-scrollbar class="chat-messages" ref="scrollbar">
      <div 
        v-for="msg in messages" 
        :key="msg.id"
        class="message-item"
        :class="{ 'bot': msg.is_bot, 'user': !msg.is_bot }"
      >
        <el-avatar 
          class="message-avatar"
          :src="msg.is_bot ? robotAvatar : userInfo.avatar?userInfo.avatar:header_image"
          :size="40"
        />
        <div class="message-content">
          <div class="message-header">
            <span class="sender">{{ msg.is_bot ? 'AI助手' : '我' }}</span>
            <span class="time">{{ formatTime(msg.timestamp) }}</span>
          </div>
          <div class="message-text">{{ msg.content }}</div>
          <div v-if="msg.is_bot" class="message-actions">
            <el-rate
              v-model="msg.rating"
              :max="5"
              @change="rateMessage(msg)"
            />
          </div>
        </div>
      </div>
    </el-scrollbar>

    <!-- 输入区域 -->
    <div class="input-area">
      <el-input
        v-model="inputMessage"
        placeholder="输入您的问题..."
        :disabled="loading"
        @keyup.enter="sendMessage"
      >
        <template #append>
          <el-button 
            type="primary" 
            :loading="loading"
            @click="sendMessage"
          >
            发送
          </el-button>
        </template>
      </el-input>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import robotAvatar from './robot-avatar.png'
import header_image from '/src/assets/header.png'
import { useUserConfig } from '/@/stores/UserInfoConfig'
import { getChatHistory, chatbot_chat, chatbot_rate } from '../../api/chatbot'
const { userInfo } = useUserConfig();
// 聊天数据
const messages = ref([])
const inputMessage = ref('')
const loading = ref(false)
const scrollbar = ref(null)
// 新增对话ID
const conversation_id = ref('') 

// 初始化加载历史记录
const loadHistory = async () => {
  try {
    const data = await getChatHistory({
        user_id: userInfo.id || 'default_user',
        // conversation_id: conversation_id.value
    })
    if (data.code === 200) {
      messages.value = data.data.map(msg => ({
        ...msg,
        rating: msg.satisfaction_rating || 0
      }))
      scrollToBottom()
    }
  } catch (error) {
    ElMessage.error('加载历史记录失败')
  }
}

// 发送消息
const sendMessage = async () => {
  if (loading.value || !inputMessage.value.trim()) return;
  const userMessage = {
    id: Date.now(),
    content: inputMessage.value,
    is_bot: false,
    timestamp: new Date().toISOString()
  }
  
  messages.value.push(userMessage)
  inputMessage.value = ''
  scrollToBottom()

  try {
    loading.value = true
    const res = await chatbot_chat({
      user_id: userInfo.id || 'default_user',
      message: userMessage.content,
      conversation_id: conversation_id.value,
    })
    if (res.code === 200) {
        conversation_id.value = res.data.conversation_id
        await loadHistory()
        scrollToBottom()
    }
  } catch (error) {
    ElMessage.error('消息发送失败')
  } finally {
    loading.value = false
  }
}

// 消息评分
const rateMessage = async (msg) => {
  try {
    await chatbot_rate({
      conversation_id: msg.conversation_id,
      message_id: msg.id,
      rating: msg.rating
    })
    ElMessage.success('评分成功')
  } catch (error) {
    ElMessage.error('评分失败')
  }
}

// 辅助函数
const formatTime = (timestamp) => {
  return dayjs(timestamp).format('HH:mm:ss')
}

const scrollToBottom = () => {
  nextTick(() => {
    scrollbar.value?.setScrollTop(scrollbar.value?.wrapRef?.scrollHeight || 0)
  })
}

onMounted(() => {
  loadHistory()
})
</script>

<style scoped>
.chat-container {
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
  /* background: #f5f7fa; */
  max-width: 800px;
  margin: 0 auto;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.message-item {
  margin: 12px 0;
  display: flex;
  justify-content: flex-start;
  gap: 12px;

  &.user {
    flex-direction: row-reverse;
    .message-avatar {
      margin-left: 12px; /* 用户头像右侧间距 */
    }
    .message-content {
      background: #409eff;
      color: white;
    }
  }
  &.bot .message-avatar {
    margin-right: 12px; /* 机器人头像左侧间距 */
  }
  &.bot .message-content {
    background: white;
    color: #333;
    border: 1px solid #ebeef5;
  }
}

.message-content {
  max-width: calc(70% - 52px);
  padding: 12px 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 0.8em;
  color: #666;
}

.user .message-header {
  color: rgba(255,255,255,0.8);
}

.message-text {
  white-space: pre-wrap;
  line-height: 1.6;
}

.message-actions {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #eee;
}

.input-area {
  padding: 20px;
  border-radius: 16px 16px 0 0;
  background: white;
  box-shadow: 0 -2px 12px rgba(0,0,0,0.05);
}
</style>
